import { nanoid } from 'nanoid';
import { Component } from 'react';
import './CommunicateWrap.css'
import axios from 'axios'
import bus from '../../util/bus';

export default class CommunicateWrap extends Component {
  constructor(props){
    super(props);
    let that = this;
    this.state = {
      useremail: this.props.useremail,
      messages:[
        {
        }
      ],
      messageInput: '',
      interviewId:  this.props.interviewId,
      client: this.props.client,
    }
  }
  render () {
    return (
      <div id="communicate-wrap">
        <ul className="communicate-room">
          {
            this.state.messages.map((message, index)=>{
              return <li key={message.id}><span>{message.useremail}:</span>   {message.message}</li>
            })
          }
        </ul>
        <div className="communicate-send-box">
          <textarea className="communicate-send-input" value={this.state.messageInput} placeholder="请输入内容" onChange={this.messageSendInputHandler}></textarea>
          <div className="communicate-send-button" onClick={this.messageSendButtonHandler}>发送</div>
        </div>
      </div>
    )
  }
  messageSendInputHandler=(e)=>{
    this.setState({
      messageInput: e.target.value,
    })
  }

  messageSendButtonHandler=()=>{
    const newMessages = [...this.state.messages];
    const message = {
      id: nanoid(),
      useremail: this.state.useremail,
      message: this.state.messageInput,
      interviewId:  this.state.interviewId,
    }

    axios.post('https://qcge2v.fn.thelarkcloud.com/addCommunicate', message).then(()=>{
      bus.emit('communicateUpdate');
      this.state.client.sendCommunicateUpdate('sendCommunicateUpdate');
    })
  }

  componentDidMount(){
    let that = this;
    let messages;
    let url = 'https://qcge2v.fn.thelarkcloud.com/getCommnicate?interviewId=';
    url += that.state.interviewId;
    axios.get(url).then((rep) => {
      messages = rep.data.result;
      this.setState({ messages: messages });
    })
    bus.on('communicateUpdate', () => {
      console.log(1);
      let messages;
      let url = 'https://qcge2v.fn.thelarkcloud.com/getCommnicate?interviewId=';
      url += that.state.interviewId;
      axios.get(url).then((rep) => {
        messages = rep.data.result;
        this.setState({ 
          messages: messages ,
          messageInput: '',
        });
      })
    })
  }
}